import 'package:flutter/material.dart';
import '../search.dart';
import '../form.dart';

import 'dart:core';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../src/call_sample/call_sample.dart';
import '../../src/call_sample/data_channel_sample.dart';
import '../../src/route_item.dart';

class Home2Page extends StatefulWidget {
  const Home2Page({super.key});

  @override
  State<Home2Page> createState() => _Home2PageState();
}

enum DialogDemoAction {
  cancel,
  connect,
}

//路由跳转
class _Home2PageState extends State<Home2Page> {
  List<RouteItem> items = [];
  String _server = '';
  late SharedPreferences _prefs;

  bool _datachannel = false;
  bool _isPrefsInitialized = false;

  @override
  void initState() {
    super.initState();
    _initData();
    _initItems();
  }

  Widget _buildRow(BuildContext context, RouteItem item) {
    return ListBody(children: <Widget>[
      ListTile(
        title: Text(item.title),
        onTap: () => item.push(context),
        trailing: Icon(Icons.arrow_right),
      ),
      Divider()
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //阴影
        elevation: 1,
        title: const Text("RTC测试"),
        //设置顶部appBar背景颜色
        backgroundColor: Colors.orange,
      ),


      //Drawer：侧边栏
      // drawer: Drawer(
      //   // child: Text("左侧侧边栏"),
      //   child: Column(
      //     children: [
      //       // SizedBox(height: 60,),
      //       Row(
      //         children: [
      //           Expanded(
      //             //让组件占满整个所选区域
      //             flex: 1,
      //             //DrawerHeader：自定义配置头部
      //             // child: DrawerHeader(
      //             //   // child: Text("头部"),
      //             //   //背景颜色及图片
      //             //   decoration: BoxDecoration(
      //             //     color: Colors.yellow,
      //             //     image: DecorationImage(
      //             //       image: NetworkImage("http://43.139.39.5:82/pho/face/1.jpg"),
      //             //       //铺满容器
      //             //       fit: BoxFit.cover,
      //             //     ),
      //             //   ),
      //             //   //昵称及头像
      //             //   child: Column(
      //             //     children: [
      //             //       ListTile(
      //             //         //在CircleAvatar配置圆形图片需要配置NetworkImage而不是Image.network
      //             //         leading: CircleAvatar(
      //             //           // child: Image.network(
      //             //           backgroundImage: NetworkImage(
      //             //             "http://43.139.39.5:82/pho/face/3.jpg",
      //             //           ),
      //             //         ),
      //             //         title: Text(
      //             //           "小优",
      //             //           style: TextStyle(
      //             //             color: Colors.white
      //             //           ),
      //             //         ),
      //             //       )
      //             //     ],
      //             //   ),
      //             // ),
      //
      //             //UserAccountsDrawerHeader：官方头部组件
      //             child: UserAccountsDrawerHeader(
      //               //姓名邮箱
      //               accountName: const Text("小优"),
      //               accountEmail: const Text("123@qq.com"),
      //               //小头像
      //               currentAccountPicture: CircleAvatar(
      //                 backgroundImage: NetworkImage(
      //                     "http://43.139.39.5:82/pho/face/1.jpg"
      //                 ),
      //               ),
      //               //其他图片
      //               otherAccountsPictures: [
      //                 Image.network("http://43.139.39.5:82/pho/face/8.jpg"),
      //                 Image.network("http://43.139.39.5:82/pho/face/9.jpg"),
      //                 Image.network("http://43.139.39.5:82/pho/face/10.jpg"),
      //               ],
      //               decoration: BoxDecoration(
      //                 //背景图片
      //                 image: DecorationImage(
      //                   //铺满容器
      //                   fit: BoxFit.cover,
      //                   image: NetworkImage("http://43.139.39.5:82/pho/face/6.jpg"),
      //                 ),
      //               ),
      //             ),
      //
      //           )
      //         ],
      //       ),
      //       ListTile(
      //         //设置成圆形图标
      //         leading: CircleAvatar(
      //           child: Icon(Icons.people),
      //         ),
      //         title: Text("个人中心"),
      //       ),
      //       Divider(),
      //       ListTile(
      //         //设置成圆形图标
      //         leading: CircleAvatar(
      //           child: Icon(Icons.settings),
      //         ),
      //         title: Text("设置"),
      //       ),
      //       Divider(),
      //       ListTile(
      //         leading: CircleAvatar(
      //           child: Icon(Icons.headphones),
      //         ),
      //         title: Text("hero"),
      //         onTap: (){
      //           //跳转hero
      //           Navigator.pushNamed(context, "/hero");
      //         },
      //       )
      //     ],
      //   ),
      // ),
      // endDrawer: const Drawer(
      //   child: Text("右侧侧边栏"),
      // ),



      body: ListView.builder(
        shrinkWrap: true,
        padding: const EdgeInsets.all(0.0),
        itemCount: items.length,
        itemBuilder: (context, i) {
          return _buildRow(context, items[i]);
        },
      ),
    );
  }

  //初始化连接
  Future<void> _initData() async {
    _prefs = await SharedPreferences.getInstance();
    setState(() {
      _server = _prefs.getString('server') ?? 'demo.cloudwebrtc.com';
      _isPrefsInitialized = true;
    });
  }

  void showDemoDialog<T>(
      {required BuildContext context, required Widget child}) {
    showDialog<T>(
      context: context,
      builder: (BuildContext context) => child,
    ).then<void>((T? value) {
      // The value passed to Navigator.pop() or null.
      if (value != null) {
        if (value == DialogDemoAction.connect) {
          if (_isPrefsInitialized) {
            _prefs.setString('server', _server);
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => _datachannel
                    ? DataChannelSample(host: _server)
                    : CallSample(host: _server),
              ),
            );
          }
        }
      }
    });
  }

  _showAddressDialog(context) {
    showDialog<DialogDemoAction>(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text('Enter server address:'),
          content: TextField(
            onChanged: (String text) {
              setState(() {
                _server = text;
              });
            },
            decoration: InputDecoration(
              hintText: _server,
            ),
            textAlign: TextAlign.center,
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('CANCEL'),
              onPressed: () {
                Navigator.pop(dialogContext, DialogDemoAction.cancel);
              },
            ),
            TextButton(
              child: const Text('CONNECT'),
              onPressed: () {
                Navigator.pop(dialogContext, DialogDemoAction.connect);
              },
            ),
          ],
        );
      },
    ).then<void>((DialogDemoAction? value) {
      if (value != null) {
        if (value == DialogDemoAction.connect) {
          if (_isPrefsInitialized) {
            _prefs.setString('server', _server);
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => _datachannel
                    ? DataChannelSample(host: _server)
                    : CallSample(host: _server),
              ),
            );
          }
        }
      }
    });
  }

  _initItems() {
    items = <RouteItem>[
      RouteItem(
        title: 'P2P Call Sample',
        subtitle: 'P2P Call Sample.',
        push: (BuildContext context) {
          _datachannel = false;
          _showAddressDialog(context);
        },
      ),
      RouteItem(
        title: 'Data Channel Sample',
        subtitle: 'P2P Data Channel.',
        push: (BuildContext context) {
          _datachannel = true;
          _showAddressDialog(context);
        },
      ),
    ];
  }
}